<template>
  <div class="page">
    <div class="toolbar">
      <el-form :inline="true" class="filters">
        <el-form-item label="关键字">
          <el-input v-model="keyword" placeholder="名称/路径" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="reload">查询</el-button>
          <el-button @click="reset">重置</el-button>
          <el-button @click="loadFlat">刷新列表</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="openCreateRoot">新建根菜单</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-area">
      <el-table :data="tree" row-key="id" style="width:100%" :tree-props="{ children: 'children' }">
        <el-table-column prop="name" label="名称" min-width="200" />
        <el-table-column prop="path" label="路径" min-width="240" />
        <el-table-column prop="icon" label="图标" width="80">
          <template #default="{ row }">
            <el-icon v-if="row.icon" :size="18">
              <component :is="getIconComponent(row.icon)" />
            </el-icon>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="order_index" label="排序" width="100" />
        <el-table-column prop="enabled" label="启用" width="100">
          <template #default="{ row }">
            <el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="{ row }">
            <el-button size="small" @click="openEdit(row)">修改</el-button>
            <el-button size="small" @click="openCreateChild(row)">创建子菜单</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog v-model="showDialog" :title="dialogTitle" width="560px" destroy-on-close>
      <el-form :model="form" label-width="100px">
        <el-form-item label="名称"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="路径"><el-input v-model="form.path" /></el-form-item>
        <el-form-item label="图标" class="icon-form-item">
          <IconPicker v-model="form.icon" />
        </el-form-item>
        <el-form-item label="父ID"><el-input v-model="form.parent_id" disabled /></el-form-item>
        <el-form-item label="排序"><el-input v-model.number="form.order_index" type="number" /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="form.enabled" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
  </template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineAsyncComponent } from 'vue'
import { api } from '../../api/client'
import IconPicker from '../../components/IconPicker.vue'

type MenuItem = { id: string; parent_id?: string | null; name: string; path: string; icon?: string | null; order_index: number; enabled: boolean }
type MenuNode = MenuItem & { children: MenuNode[] }

const flat = ref<MenuItem[]>([])
const tree = ref<MenuNode[]>([])
const keyword = ref('')

function buildTree(items: MenuItem[]): MenuNode[] {
  const map: Record<string, MenuNode> = {}
  const roots: MenuNode[] = []
  items.forEach(m => { map[m.id] = { ...m, children: [] } })
  items.forEach(m => {
    const node = map[m.id]
    const pid = m.parent_id || ''
    if (pid && map[pid]) map[pid].children.push(node)
    else roots.push(node)
  })
  const idx: Record<string, number> = {}
  items.forEach(m => { idx[m.id] = m.order_index })
  const sortChildren = (n: MenuNode[]) => n.sort((a,b) => (idx[a.id]||0) - (idx[b.id]||0))
  const dfs = (n: MenuNode[]) => { sortChildren(n); n.forEach(c => dfs(c.children)) }
  dfs(roots)
  return roots
}

async function loadFlat() {
  const resp = await api.get('/menus/')
  flat.value = resp.data
  applyFilter()
}

function applyFilter() {
  const kw = keyword.value.trim()
  if (!kw) { tree.value = buildTree(flat.value); return }
  const matchedIds = new Set(flat.value.filter(m => (m.name?.includes(kw) || m.path?.includes(kw))).map(m => m.id))
  const keep = flat.value.filter(m => matchedIds.has(m.id) || (m.parent_id && matchedIds.has(m.parent_id)))
  tree.value = buildTree(keep.length ? keep : flat.value)
}

function reload() { applyFilter() }
function reset() { keyword.value = ''; applyFilter() }

const showDialog = ref(false)
const dialogTitle = ref('新建菜单')
const saving = ref(false)
const editingId = ref<string | null>(null)
const form = reactive<any>({ name: '', path: '', parent_id: '', order_index: 0, enabled: true, icon: '' })

function openCreateRoot() {
  dialogTitle.value = '新建根菜单'
  editingId.value = null
  Object.assign(form, { name: '', path: '', parent_id: '', order_index: 0, enabled: true, icon: '' })
  showDialog.value = true
}

function openCreateChild(row: MenuItem) {
  dialogTitle.value = '新建子菜单'
  editingId.value = null
  Object.assign(form, { name: '', path: '', parent_id: row.id, order_index: 0, enabled: true, icon: '' })
  showDialog.value = true
}

function openEdit(row: MenuItem) {
  dialogTitle.value = '修改菜单'
  editingId.value = row.id
  Object.assign(form, { name: row.name, path: row.path, parent_id: row.parent_id || '', order_index: row.order_index, enabled: row.enabled, icon: row.icon || '' })
  showDialog.value = true
}

async function submit() {
  saving.value = true
  try {
    if (editingId.value) {
      await api.put(`/menus/${editingId.value}`, { name: form.name, path: form.path, order_index: form.order_index, enabled: form.enabled, icon: form.icon, parent_id: form.parent_id || null })
    } else {
      const payload: any = { name: form.name, path: form.path, order_index: form.order_index, enabled: form.enabled, icon: form.icon }
      if (form.parent_id) payload.parent_id = form.parent_id
      await api.post('/menus/', payload)
    }
    showDialog.value = false
    await loadFlat()
  } finally { saving.value = false }
}

onMounted(loadFlat)

// 获取图标组件
function getIconComponent(iconName: string) {
  if (!iconName) return null
  return defineAsyncComponent(() => 
    import('@element-plus/icons-vue').then(module => {
      if (module[iconName as keyof typeof module]) {
        return module[iconName as keyof typeof module]
      }
      // 如果Element Plus中没有，尝试从Lucide图标库导入
      return import('lucide-vue-next').then(lucideModule => {
        return lucideModule[iconName as keyof typeof lucideModule] || null
      })
    }).catch(() => {
      return null
    })
  )
}
</script>

<style scoped>
.page { height: 100%; display: flex; flex-direction: column; }
.toolbar { display: flex; align-items: center; }
.filters { flex: 1; display: flex; align-items: center; gap: 12px; }
.table-area { flex: 1; min-height: 0; }
.table-area :deep(.el-table__body-wrapper) { height: 100%; overflow: auto; }

/* 图标表单项样式 */
.icon-form-item :deep(.el-form-item__content) {
  display: block;
}
</style>
